package com.yanqu.road.server.cmd.ping;

import com.yanqu.road.entity.enums.ePlayerAttrType;
import com.yanqu.road.entity.player.PlayerState;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.pb.login.LoginProto;
import com.yanqu.road.server.agent.inter.AgentPlayer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.AttributeModule;
import com.yanqu.road.server.gameplayer.module.player.DailyDataModule;
import com.yanqu.road.server.manger.ForbiddenIpMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.utils.LocalDateTimeHelper;

@Cmd(code = Protocol.S_PLAYER_PING, desc = "客户端心跳")
public class PingCmd extends AbstractCommand {

	@Override
	public boolean parseData(YanQuMessage packet) throws Exception {
		return true;
	}

	@Override
	public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
		long nowTimeNano = System.currentTimeMillis();
		int nowTime = (int) (System.currentTimeMillis() / 1000);
		LoginProto.PingDataMsg.Builder pingMsg = LoginProto.PingDataMsg.newBuilder();
		pingMsg.setTime(nowTime);
		pingMsg.setTimeZone(LocalDateTimeHelper.getDefaultTimeZone());
		pingMsg.setNanoTime(nowTimeNano);
		if (player != null) {
			long sT = nowTime - (UserMgr.T / 1000);
			if (sT >= 0 && sT < 60 * 5) {
				pingMsg.setE(UserMgr.K);
				player.setSend(player.getSend() + 1);
				AttributeModule attributeModule = player.getModule(AttributeModule.class);

				long oV = 0;
				if (attributeModule.hasAttribute(ePlayerAttrType.TK_ERROR)) {
					oV = attributeModule.getAttribute(ePlayerAttrType.TK_ERROR);
				}
				long d = player.getSend() - player.getRec();
				if (d > 5 && d > oV) {
					attributeModule.setAttribute(ePlayerAttrType.TK_ERROR, d);
				}
				if (d > 5) {
					attributeModule.setAttribute(ePlayerAttrType.TK_ERROR, d);
				}
			}
			//加个计算直播时间的动作
			player.getModule(DailyDataModule.class).calcLiveShowTime(false,  false);
			player.setLastPingTime(System.currentTimeMillis());
			player.setState(PlayerState.ONLINE);
			player.sendPacket(Protocol.U_PLAYER_PING, pingMsg);

			if (sT > (60 * 5) && sT < (60 * 10) && (player.getSend() - player.getRec()) > 20 ) {
				player.setSend(0);
				player.setRec(0);
				player.getUserInfo().setBlackListEndTime(System.currentTimeMillis() + ChannelConfig.WAI_GUA_FORBIDDEN_TIME * 60 * 1000);
				ForbiddenIpMgr.add(player.getWebSocketIp());
				AgentPlayer.executeKillPlayer(player.getUserInfo().getUserId());
			}
		}
	}

	@Override
	public void sendData(GamePlayer player) {

	}

}
